package org.scratchcrew.web.cometd.continuation;

import java.util.Map;

import javax.servlet.ServletException;

import org.cometd.server.continuation.ContinuationCometdServlet;
import org.scratchcrew.web.cometd.SpringContinuationBayeux;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 
 *A subclass of {@link ContinuationCometdServlet} which finds the bayeux in the
 * spring application context.
 * 
 */
public class SpringContinuationCometdServlet extends ContinuationCometdServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2304624159962009570L;
	private static final String REFS_THRESHOLD_PARAMETER_NAME = "refsThreshold";

	/**
	 * 
	 * <p>
	 * Overrides <code>AbstractCometdServlet.init()</code> because
	 * {@link SpringContinuationBayeux} handles it's own initialization.
	 * </p>
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void init() throws ServletException {
		synchronized (SpringContinuationCometdServlet.class) {
			log("Initailizng SpringContinuationCometdServlet.");
			WebApplicationContext webApplicationContext = WebApplicationContextUtils
					.getRequiredWebApplicationContext(getServletContext());
			Map<String, SpringContinuationBayeux> bayexBeansMap = webApplicationContext
					.getBeansOfType(SpringContinuationBayeux.class);
			if (bayexBeansMap == null || bayexBeansMap.size() != 1) {
				throw new ServletException("Unable to find a unique"
						+ " Spring bean of the type SpringContinuationBayeux.");

			}
			_bayeux = bayexBeansMap.values().iterator().next();

			String refsThreshold = getInitParameter(REFS_THRESHOLD_PARAMETER_NAME);
			if (refsThreshold != null)
				_refsThreshold = Integer.parseInt(refsThreshold);
		}
	}
}
